package com.dz.core.component.filter;

import com.dz.core.component.support.JwtBean;
import com.dz.core.component.cache.RedisCache;
import com.dz.core.config.properties.JwtProperties;
import com.dz.core.constant.ResCode;
import com.dz.core.util.RenderUtil;
import com.google.common.base.Strings;
import io.jsonwebtoken.JwtException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author fengshuonan
 * @Date 2017/8/24 14:04
 */
public class AuthFilter extends OncePerRequestFilter {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private JwtBean jwtBean;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request.getRequestURI().equals("/" + jwtProperties.getAuthPath())) {
            chain.doFilter(request, response);
            return;
        }
        final String requestHeader = request.getHeader(jwtProperties.getHeader());

        if (Strings.isNullOrEmpty(requestHeader)) {
            //header没有带Bearer字段
            RenderUtil.renderToResBody(response,ResCode.TOKEN_LOSE);
            return;
        }

        String authToken = requestHeader;
        //验证token是否过期
        try {
            boolean flag = jwtBean.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderToResBody(response,ResCode.TOKEN_EXPIRATION);
                return;
            }

            if(!redisCache.hasKey(authToken)){
                RenderUtil.renderToResBody(response,ResCode.INVALID_TOKEN);
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderToResBody(response,ResCode.INVALID_TOKEN);
            return;
        }

        chain.doFilter(request, response);
    }
}